import { MiddlewareConsumer, Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_INTERCEPTOR } from '@nestjs/core';
import * as Joi from 'joi';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ResSuccessInterceptor } from './common/interceptor/res-success.interceptor';
import { LoggerModule } from './common/logger/logger.module';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { TypeormModule } from './common/typeorm/typeorm.module';
import { DeptsModule } from './modules/depts/depts.module';
import { DictDataModule } from './modules/dicts-data/dicts-data.module';
import { DictModule } from './modules/dicts/dicts.module';
import { MenusModule } from './modules/menus/menus.module';
import { RolesModule } from './modules/roles/roles.module';
import { UsersModule } from './modules/users/users.module';
import { AuthModule } from './modules/auth/auth.module';
import { CacheModule } from '@nestjs/cache-manager';
import { RedisCacheModule } from './common/redis/redis.module';
import { JwtAuthGuard } from './common/guards/jwt-auth.guard';
import { LogsModule } from './modules/app-logs/app-logs.module';
import { NoticesModule } from './modules/notices/notices.module';
import { UploadModule } from './common/upload/upload.module';
import { MinioService } from './common/upload-minio/minio.service';
import { MinioModule } from './common/upload-minio/minio.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: [`.env.${process.env.NODE_ENV}`, '.env'],
      // 环境变量校验
      validationSchema: Joi.object({
        // 环境变量校验
        NODE_ENV: Joi.string().valid('development', 'production'),
        // 数据库配置
        DB_TYPE: Joi.string().valid('mysql', 'mariadb'),
        DB_HOST: Joi.string().ip().required(),
        DB_PORT: Joi.number().default(3306),
        DB_ACCOUNT: Joi.string().required(),
        DB_PASSWD: Joi.string().required(),
        DB_DATABASE: Joi.string().required(),
        DB_SYNC: Joi.boolean().default(false),
      }),
    }),
    CacheModule.register({ isGlobal: true }),
    UsersModule,
    DeptsModule,
    RolesModule,
    MenusModule,
    TypeormModule,
    LoggerModule,
    DictModule,
    DictDataModule,
    AuthModule,
    RedisCacheModule,
    LogsModule,
    NoticesModule,
    UploadModule,
    MinioModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    MinioService,
    {
      // 全局守卫拦截 // 配置全局守卫 app.useGlobalGuards(new JwtAuthGuard(app.get(Reflector))); 无法使用调用Services
      provide: 'APP_GUARD',
      useClass: JwtAuthGuard,
    },
    {
      provide: APP_INTERCEPTOR,
      useClass: ResSuccessInterceptor,
    },
  ],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
